package com.cx.auth.impl;

import com.cx.po.SysUser;
import com.cx.po.SysUserRole;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 *
 * Author:CHENXIAOYI
 * Since:2020/12/25 14:14
 */
@Service
@Slf4j
public class UserDetailServiceImpl implements UserDetailsService {

    private final MongoTemplate mongoTemplate;


    public UserDetailServiceImpl(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }

    /**
     * 登陆逻辑处理
     *  可设置连续错误五次锁定账户等
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = mongoTemplate.findOne(new Query(Criteria.where("username").is(username)), SysUser.class);
        if(sysUser == null){
            throw new UsernameNotFoundException("您的登录账号输入错误！");
        }
        List<SysUserRole> userRoles = mongoTemplate.find(new Query(Criteria.where("userId").is(sysUser.getId())), SysUserRole.class);
        sysUser.setAuths(userRoles.stream().map(SysUserRole::getRoleId).collect(Collectors.toList()));
        return sysUser;
    }
}
